import { css } from "@emotion/react"
import { LoginOtpForm } from "../data"
import { useEffect, useMemo, useRef, useState } from "react"
import { motion } from "motion/react"
import styled from "@emotion/styled"
import Svg, { SvgComponent } from "@/components/base/Svg"
import { createLogger } from "@/utils/logger"

const logger = createLogger("PhoneInputFormItem")

const Container = styled(motion.div)`
    display: flex;
    flex-direction: row;
    gap: 1rem;
    border-radius: 8rem;
    background-color: #f3f3f7;
`
const ClearButton = styled(SvgComponent("login/clear_field.svg"))`
    width: 100%;
    height: 100%;
`

type Props = Omit<ExtractStyledProps<typeof Container>, "children">
export default function PhoneInputFormItem({ ...props }: Props) {
    const {
        //
        className: _className,
        style: _style,
        css: _css,
        ...rest
    } = props
    const [focused, setFocused] = useState(false)
    const form = LoginOtpForm.useFormContext()
    const focusedOrHasValue = form.watch("number") || focused
    const inputRef = useRef<HTMLInputElement>(null)

    const errorMessage = [form.formState.errors.number?.message].filter(Boolean).shift()

    const showErrorMessage = useMemo(() => {
        return errorMessage && form.formState.submitCount > 0
    }, [errorMessage, form.formState.submitCount])

    const boxShadow = useMemo(() => {
        if (showErrorMessage) {
            return "0 0 1rem 1rem #cc0033 inset"
        }
        if (!form.formState.errors.number && focusedOrHasValue && form.formState.isValid) {
            return "0 0 1rem 1rem #00c52b inset"
        }
        if (focusedOrHasValue) {
            return "0 0 1rem 1rem #165dff inset"
        }
        return "0 0 1rem 1rem #b8bdcc inset"
    }, [focusedOrHasValue, form.formState.errors.number, form.formState.isValid, showErrorMessage])

    useEffect(() => {
        if (inputRef.current) {
            setTimeout(() => {
                inputRef.current?.focus()
                inputRef.current?.click()
            }, 100)
        }
    }, [])

    return (
        <LoginOtpForm.ErrorWrapper
            css={css`
                display: flex;
                flex-direction: column;
                gap: 8rem;
                align-items: stretch;
            `}
            field="number"
            render={() => {
                return (
                    <motion.caption
                        initial={{
                            opacity: 0,
                        }}
                        animate={{
                            opacity: showErrorMessage ? 1 : 0,
                        }}
                        css={css`
                            color: #cc0033;
                            align-self: flex-start;
                            display: flex;
                            flex-direction: row;
                            gap: 4rem;
                            align-items: center;
                            font-size: 12rem;
                            line-height: 16rem;
                            font-weight: 500;
                            font-family: "Gilroy", monospace;
                            height: 20rem;
                        `}
                    >
                        <Svg
                            css={css`
                                width: 16rem;
                                height: 16rem;
                            `}
                            src="login/error_head.svg"
                        />
                        {errorMessage}
                    </motion.caption>
                )
            }}
        >
            <Container
                style={{
                    ..._style,
                }}
                initial={{
                    boxShadow: "0 0 1rem 1rem #b8bdcc inset",
                }}
                animate={{
                    boxShadow,
                    backgroundColor: showErrorMessage ? "#FEE0E7" : undefined,
                }}
                css={css`
                    position: relative;
                    display: flex;
                    flex-direction: row;
                    gap: 1rem;
                    border-radius: 8rem;
                    background-color: #f3f3f7;
                    height: 56rem;
                    justify-content: center;
                    align-items: center;
                    padding: 0 16rem;
                    cursor: text;

                    > input,
                    > select {
                        border: none;
                        font-size: 16rem;
                        line-height: 24rem;
                        font-weight: 500;
                        color: #3e4046;
                        font-family: "Gilroy", monospace;
                        box-sizing: border-box;
                        /* disable input default style */
                        outline: none;
                        background-color: transparent;
                        &:focus {
                            outline: none;
                        }
                        &::placeholder {
                            color: #9ca3b4;
                        }
                    }
                `}
                className={_className}
                onClick={() => {
                    inputRef.current?.focus()
                }}
            >
                <motion.div
                    css={css`
                        position: absolute;
                        top: 8rem;
                        left: 16rem;
                        font-size: 12rem;
                        line-height: 16rem;
                        font-weight: 500;
                        font-family: "Gilroy", monospace;
                        color: #6a7081;
                    `}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: focusedOrHasValue ? 1 : 0 }}
                >
                    Phone number
                </motion.div>
                <LoginOtpForm.BaseItem
                    label="Country Code"
                    field="countryCode"
                    options={{
                        required: true,
                        validate: (value) => {
                            if (value.length !== 3) {
                                return "Country code must be 3 characters"
                            }
                            return true
                        },
                    }}
                    render={({ methods }) => (
                        <motion.select
                            css={css`
                                /* hide the default arrow */
                                appearance: none;
                                > option {
                                    white-space: nowrap;
                                }
                            `}
                            disabled
                            initial={{
                                opacity: 0,
                                width: "0rem",
                                marginTop: "auto",
                                marginBottom: "16rem",
                            }}
                            animate={{
                                opacity: focusedOrHasValue ? 1 : 0,
                                width: focusedOrHasValue ? "40rem" : "0rem",
                                marginTop: focusedOrHasValue ? "auto" : "auto",
                                marginBottom: focusedOrHasValue ? "8rem" : "16rem",
                            }}
                            transition={{
                                duration: 0.3,
                            }}
                            onChange={(e) => {
                                methods.setValue("countryCode", e.target.value)
                            }}
                        >
                            <option value="+63">+63</option>
                            <option value="+64">+64</option>
                            <option value="+65">+65</option>
                            <option value="+66">+66</option>
                            <option value="+67">+67</option>
                            <option value="+68">+68</option>
                            <option value="+69">+69</option>
                        </motion.select>
                    )}
                />
                <LoginOtpForm.BaseItem
                    label="Number"
                    field="number"
                    options={{
                        validate: (value) => {
                            const formattedValue = value.split(" ").join("")
                            if (formattedValue.length === 0) {
                                return "Phone number is required"
                            }
                            if (formattedValue.length < 10) {
                                return "Sorry, it's not a valid phone number, should be 10 digits"
                            }
                            return true
                        },
                    }}
                    render={({ methods }) => {
                        const number = methods.watch("number")
                        const numberLength = (() => {
                            if (number.startsWith("09")) {
                                return 13 // 11位數字 + 2個破折號
                            }
                            if (number.startsWith("9")) {
                                return 12 // 10位數字 + 2個破折號
                            }
                            return 2 // 限制只能輸入09或9開頭
                        })()

                        // 格式化電話號碼，去掉前導 0
                        const formatPhoneNumber = (input: string) => {
                            // 移除所有非數字字符
                            let numbersOnly = input.replace(/\D/g, "")

                            // 如果以 09 開頭，去掉 0
                            if (numbersOnly.startsWith("09")) {
                                numbersOnly = numbersOnly.substring(1) // 去掉 0，只保留 9 開頭
                            }

                            // 確保以 9 開頭
                            if (!numbersOnly.startsWith("9") && numbersOnly.length > 0) {
                                numbersOnly = "9" + numbersOnly.slice(1)
                            }

                            // 統一格式為 9XX XXX XXXX
                            if (numbersOnly.length > 3) {
                                if (numbersOnly.length > 6) {
                                    return `${numbersOnly.slice(0, 3)} ${numbersOnly.slice(3, 6)} ${numbersOnly.slice(6, 10)}`
                                }
                                return `${numbersOnly.slice(0, 3)} ${numbersOnly.slice(3)}`
                            }

                            return numbersOnly
                        }

                        const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
                            let value = e.target.value

                            // 檢查首字符
                            if (value.length === 1 && value !== "0" && value !== "9") {
                                if (value.match(/\d/)) {
                                    // 如果是數字但不是0或9，替換為9
                                    value = "9"
                                } else {
                                    // 如果不是數字，則忽略
                                    value = ""
                                }
                            }

                            // 檢查第二個字符（如果第一個是0）
                            if (value.length === 2 && value.startsWith("0") && value[1] !== "9") {
                                if (value[1].match(/\d/)) {
                                    // 如果第二個字符是數字但不是9，替換為9
                                    value = "09"
                                } else {
                                    // 如果不是數字，保留0
                                    value = "0"
                                }
                            }

                            // 獲取輸入值並格式化
                            const formattedValue = formatPhoneNumber(value)

                            // 設置格式化後的值
                            methods.setValue("number", formattedValue)
                            methods.trigger("number")
                        }

                        return (
                            <motion.input
                                ref={inputRef}
                                css={css`
                                    flex: 1;
                                    caret-color: #1e71ff;
                                    margin: auto;
                                    white-space: nowrap;
                                    /* 確保元素可以正常交互 */
                                    user-select: text;
                                    pointer-events: auto;
                                `}
                                initial={{
                                    opacity: 1,
                                    width: "0rem",
                                    transform: "translateY(0rem)",
                                }}
                                animate={{
                                    opacity: focusedOrHasValue ? 1 : 0.5,
                                    width: focusedOrHasValue ? "30rem" : "0rem",
                                    transform: focusedOrHasValue
                                        ? "translateY(8rem)"
                                        : "translateY(0rem)",
                                }}
                                onFocus={(ev) => {
                                    setFocused(true)
                                    ev.currentTarget.click()
                                }}
                                onBlur={() => setFocused(false)}
                                type="tel"
                                placeholder={focused ? "" : "Phone number"}
                                inputMode="tel"
                                maxLength={numberLength}
                                onChange={handleChange}
                                value={methods.watch("number")}
                                onPaste={(e) => {
                                    e.preventDefault()
                                    const pastedText = e.clipboardData.getData("text")
                                    let numbersOnly = pastedText.replace(/\D/g, "")

                                    // 去掉前導 0
                                    if (numbersOnly.startsWith("0")) {
                                        numbersOnly = numbersOnly.substring(1)
                                    }

                                    // 確保以 9 開頭
                                    if (!numbersOnly.startsWith("9") && numbersOnly.length > 0) {
                                        numbersOnly = "9" + numbersOnly.slice(1)
                                    }

                                    const formattedValue = formatPhoneNumber(numbersOnly)
                                    methods.setValue("number", formattedValue)
                                    methods.trigger("number")
                                }}
                            />
                        )
                    }}
                />
                <motion.div
                    css={css`
                        width: 14rem;
                        height: 14rem;
                        position: absolute;
                        right: 16rem;
                        transform-origin: center;
                        cursor: pointer;
                        border-radius: 8rem;
                    `}
                    initial={{
                        opacity: 0,
                        scale: 0.8,
                        visibility: "hidden",
                        boxShadow: "none",
                    }}
                    animate={{
                        opacity: form.watch("number") ? 1 : 0,
                        scale: form.watch("number") ? 1 : 0.8,
                        visibility: form.watch("number") ? "visible" : "hidden",
                        boxShadow: form.watch("number") ? "1rem 1rem 1rem 0rem #ababab" : "none",
                    }}
                >
                    <ClearButton
                        onClick={() => {
                            form.setValue("number", "")
                            form.trigger("number")
                        }}
                    />
                </motion.div>
            </Container>
        </LoginOtpForm.ErrorWrapper>
    )
}
